<template>
  <div
    :class="['unitWrapper', 'demo-autocomplete']"
    :id="'scroll' + thirdScrollIndex + '-0'"
  >
    <div class="unitTop">
      <div class="unitTitleContainer">
        <div class="unitFlag"></div>
        <div class="unitTitle">{{ chartTitle }}</div>
      </div>
      <div class="saveBtns" v-if="!isSuperToken && false">
        <div class="contentItemEditAndAIBtn AIBtn" @click="aiCreate()">
          <img src="@/assets/detail/AI_white.png" />
          {{ aiCreateStatus ? 'AI正在生成中 . . .' : 'AI生成' }}
        </div>
        <div class="contentItemEditAndAIBtn" @click="handleEditClick">
          <img src="@/assets/detail/edit_white.png" />
          {{ currentEdit ? '退出编辑' : '编辑' }}
        </div>
        <div
          class="contentItemEditAndAIBtn saveEditBtn"
          @click="save()"
          v-if="isAdmin == true && currentEdit"
        >
          <!-- <img src="@/assets/detail/save.png" /> -->
          保存
        </div>
      </div>
    </div>
    <div
      :class="{
        allwrapper: true,
        inEdit: extendContent.length,
        blueBorder: currentEdit
      }"
    >
      <div
        :class="{ unitContent: true, colunmDirection: extendContent.length }"
      >
        <div :class="{ firstItem: true }">
          <div class="summaryContainer">
            <p class="summaryTitle">
              <span class="summaryFlag"></span> 该职业的{{
                chartTitle
              }}主要集中在{{ maxType }}
            </p>
            <p v-if="!currentEdit" class="summaryContent">{{ summary }}</p>
            <el-input
              v-model="editSummary"
              type="textarea"
              resize="none"
              autosize
              v-if="currentEdit && summary"
            />
          </div>
        </div>
        <div class="secondItem">
          <div class="itemForDisplay">
            <span class="editTips" v-show="currentEdit">
              点击图表数字标签可以直接修改数据
            </span>
            <div class="h100" ref="line_echartDom"></div>
          </div>
        </div>
      </div>
      <div
        :class="{ itemForEdit: true, inEdit: currentEdit }"
        v-if="extendContent.length"
      >
        <div :class="{ editBoxRight: true }">
          <div
            v-for="(item, index) in extendContent"
            class="extendsItem"
            :key="index"
          >
            <!-- <div v-html="item"></div> -->
            <el-input
              type="textarea"
              autosize
              placeholder="请输入内容"
              v-model="item.content"
            />
            <div
              class="replaceByOne"
              @click="replaceByOne('second', item)"
              v-if="currentEdit"
            >
              一键替换
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  homepageQuestion,
  valueListAnalysis,
  valueListUpdate,
  valueLayerValueAnalysis
} from '@/api/position-detail';
import { MessageBox } from 'element-ui';
import { addLog } from '@/api/position';
export default {
  props: {
    layerData: {
      type: Object,
      default: () => {}
    },
    layerId: {
      type: [Number, String],
      require: true
    },
    thirdScrollIndex: {
      type: Number || String,
      default: 1
    },
    isSuperToken: {
      type: Boolean,
      default: false
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  name: 'radarChartBigger',
  mounted() {
    this.positionId = this.$route.query.id;
    this.init();
  },
  data() {
    return {
      chartAreaColor: null,
      chartAreaLineColor: null,
      maxType: '',
      currentEdit: false,
      originChartData: '',
      secondQuestionId: '',
      chartData: { chartNameData: [], chartValueData: [] },
      extendContent: [],
      firstMessages: [],
      chartTitle: '',
      positionId: '',
      summary: '', //总结话语
      editSummary: '',
      myChart: ''
    };
  },
  methods: {
    checkCostomColor() {
      let chartAreaFirstColor, chartAreaLastColor, chartAreaLineColor;

      switch (this.layerId) {
        // 性格要求，黄色
        case '20':
          chartAreaFirstColor = '#FFA45D';
          chartAreaLastColor = 'rgba(250,213,88,0.2)';
          chartAreaLineColor = '#FFA542';
          break;

        default:
          //默认蓝色
          chartAreaFirstColor = 'rgba(0, 78, 255, 0.5)';
          chartAreaLastColor = 'rgba(88, 122, 250, 0.1)';
          chartAreaLineColor = '#4283FF';
          break;
      }
      this.chartAreaLineColor = chartAreaLineColor;
      this.chartAreaColor = new this.$echarts.graphic.RadialGradient(
        0.5,
        0,
        1,
        [
          {
            color: chartAreaFirstColor,
            offset: 0
          },
          {
            color: chartAreaLastColor,
            offset: 1
          }
        ]
      );
    },
    save() {
      if (this.aiCreateStatus) {
        this.$message({
          type: 'warning',
          message: '已有AI正在生成中，请等待生成内容结束!'
        });
        return;
      }
      this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        //后面在看看怎么保存表单的
        this.summary = this.editSummary;
        this.originChartData[this.originChartData.length - 1].layerValue =
          this.editSummary;
        this.updateLayerValuebySave(this.originChartData, this.originChartData);
        this.extendContent = [];
        this.$set(this.layerData, 'hasExtendContent', true);
        this.$nextTick(() => {
          this.myChart.resize();
        });
        this.currentEdit = false;
      });
    },
    replaceByOne(flag, val) {
      let questionId = this.secondQuestionId;
      const params = {
        questionContent: val.content.replace(/<br>/g, ' '),
        id: questionId,
        ylPositionId: this.positionId
      };
      valueListAnalysis(params).then((res) => {
        if (res.code == 200) {
          this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.chartData.chartNameData = [];
            this.chartData.chartValueData = [];
            res.data.forEach((item) => {
              if (!item.description || !item.layerValue) return;

              if (item.description == '总结') {
                this.summary = item.layerValue;
                this.editSummary = item.layerValue;
                this.originChartData.forEach((oriItem, oriIndex) => {
                  if (oriItem.description == item.description) {
                    oriItem.layerValue = item.layerValue;
                  }
                });
                return;
              }
              this.chartData.chartNameData.push({
                max: 5,
                description: item.description,
                value: item.layerValue
              });
              this.chartData.chartValueData.push(item.layerValue);
            });
            //还要发送请求给后端保存。。。
            this.originChartData = res.data;
            this.updateLayerValuebyReplace(params, this.originChartData);
            this.init();
          });
        } else {
          //console.log("内容解析失败了！请尝试重新生成！");
        }
      });
    },
    //用于一键替换保存的，params直接传入未解析的AI生成内容
    updateLayerValuebyReplace(params, listData) {
      valueListUpdate(params).then((res) => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      });
    },
    //用于保存按钮保存的,params是数组
    updateLayerValuebySave(params, listData) {
      valueLayerValueAnalysis(params).then((res) => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      });
    },
    handleEditClick() {
      this.currentEdit = !this.currentEdit;
      if (this.currentEdit) {
        this.editSummary = this.summary;
        this.$message({
          type: 'success',
          message: '点击雷达图的标签可以单个编辑数据',
          offset: 400
        });
      } else {
      }
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.checkCostomColor();
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let indicator = this.chartData.chartNameData,
        value = this.chartData.chartValueData;
      if (!indicator.length || !value.length) {
        return;
      }
      const that = this;
      let option = {
        color: [this.chartAreaLineColor],
        radar: [
          {
            center: ['50%', '50%'],
            indicator,
            radius: '60%',
            splitNumber: 5,
            nameGap: 10,
            silent: true,
            triggerEvent: true,
            axisName: {
              formatter: function (value, indicator) {
                const name = indicator.description;
                const realValue = indicator.value;
                return `{a|${name}}\n{b|${realValue}}`;
              },
              rich: {
                a: {
                  color: '#555',
                  fontSize: 15,
                  lineHeight: 28
                },
                b: {
                  fontFamily: 'D-DIN-PRO-500-Medium',
                  fontWidth: 'bold',
                  color: '#4880FF',
                  align: 'left',
                  fontSize: 26,
                  padding: [0, 0, 0, 6]
                }
              },
              textStyle: {
                color: '#fff'
              }
            },
            axisLine: {
              lineStyle: {
                color: '#B8D6FD',
                width: 0.5
              }
            },
            splitLine: {
              lineStyle: {
                color: [
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#B8D4F2'
                ]
              }
            }
          }
        ],
        series: [
          {
            type: 'radar',
            emphasis: {
              lineStyle: {
                width: 4,
                color: this.chartAreaLineColor
              }
            },
            data: [
              {
                value,
                areaStyle: {
                  color: this.chartAreaColor,
                  borderColor: this.chartAreaLineColor
                },
                itemStyle: {
                  // 设置连接线不可见
                  opacity: 0
                }
              }
            ]
          }
        ]
      };

      try {
        option && this.myChart.setOption(option);
      } catch (error) {
        //console.log("erro", this);
      }
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.on('click', function (params) {
        if (params.componentType === 'radar' && that.currentEdit) {
          var regex = /\{([a-z])\|([^}]+)\}/g;
          var match;
          match = regex.exec(params.name);
          const nowName = match[2];
          MessageBox.prompt(`请输入${nowName}新的值：`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^(5(\.0)?|[0-4](\.\d)?)$/,
            inputErrorMessage: '输入格式不正确'
          })
            .then(({ value }) => {
              that.handleChartValueChange(nowName, value);
            })
            .catch((e) => {
              //console.log("e", e);
              this.$message.info('取消输入');
            });
        }
      });
    },
    handleChartValueChange(nowName, value) {
      let maxValue = 0;
      this.originChartData.forEach((item) => {
        if (item.description == nowName) {
          item.layerValue = value;

          this.chartData.chartNameData.forEach((item, index) => {
            if (item.description == nowName) {
              item.value = value;
              this.chartData.chartValueData[index] = value;
              this.myChart.off('click');
              this.init();
            }

            if (maxValue < +item.value) {
              this.maxType = item.description;
              maxValue = item.value;
            }
          });
          this.updateLayerValuebySave(this.originChartData);
        }
      });
    },
    async aiCreate() {
      if (this.aiCreateStatus) {
        this.$message({
          type: 'warning',
          message:
            '已有AI正在生成中，等待生成内容结束或F5刷新页面再次点击AI生成!'
        });
        return;
      } else {
        // this.currentEdit = true;
        let textEl = document.querySelectorAll('.AIBtn'); // 获取要添加省略号的元素
        textEl.forEach((item) => {
          item.classList.add('AILoading'); // 添加类名，启动动画效果
        });
      }

      //获取问题
      const name =
        this.$route.query.name != undefined ? this.$route.query.name : '';

      const questionRes1 = await this.reqGetQuestionbyId(this.secondQuestionId);
      this.chatKey1 = questionRes1.data.questionContent.replace(/{}/g, name);

      //同时发送两个问题给chatGPT
      this.firstMessages.push({
        role: 'user',
        content: this.chatKey1
      });
      const agentData1 = {
        userId: '',
        userName: '',
        messages: this.firstMessages
      };
      this.firstMessages = [];
      this.sendMsg1 = JSON.stringify(agentData1);

      this.$set(this.extendContent, this.extendContent.length, { content: '' });
      // this.$emit("update:layerData",{...this.layerData})
      try {
        this.$bus.$emit(
          'send',
          this.sendMsg1,
          this.initMessageBackForFirst,
          this.wsError
        );
      } catch (error) {
        //console.log("发送ws报错", error);
      }

      this.$message.success({
        message: 'AI生成内容中...',
        offset: '400'
      });
      addLog({ logType: '10' });
    },
    initMessageBackForFirst(res) {
      const msg = res.choices && res.choices[0];
      if (msg.delta.role === 'assistant') {
        return;
      }
      if (msg.finish_reason === 'stop' || msg.finish_reason === 'done') {
        this.loading = false;
        this.currentRole = '';

        let textEl = document.querySelectorAll('.AIBtn');
        textEl.forEach((item) => {
          item.classList.remove('AILoading');
        });

        return;
      }
      if (msg.delta.content) {
        var tempStr = msg.delta.content;
        if (tempStr) {
          tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, '<br>');
        }
        let len = this.extendContent ? this.extendContent.length - 1 : 0;
        this.$set(
          this.extendContent[len],
          'content',
          (this.extendContent[len].content += tempStr)
        );
      }
    },
    reqGetQuestionbyId(questionId) {
      return homepageQuestion({ questionId });
    },
    wsError() {
      //console.log("连接失败，请重试");
    }
  },
  watch: {
    layerData: {
      handler(newValue, oldValue) {
        const item = newValue;
        this.chartTitle = item.title;
        let maxValue = 0;
        this.originChartData = item.data.map((item, index) => {
          if (item.description == '总结') {
            return item;
          }

          item.layerValue = (+item.layerValue).toFixed(1);
          if (maxValue < item.layerValue) {
            this.maxType = item.description;
            maxValue = item.layerValue;
          }
          return item;
        });
        item.data.forEach((item) => {
          if (item.description == '总结') {
            this.summary = item.layerValue;
            return;
          }

          if (!this.secondQuestionId) {
            this.secondQuestionId = item.questionId;
          }
          try {
            this.chartData.chartNameData.push({
              max: 5,
              description: item.description,
              value: item.layerValue
            });
            this.chartData.chartValueData.push(item.layerValue);
          } catch (error) {
            //console.log("error", error);
          }
        });
      },
      immediate: true
    }
  }
};
</script>

<style lang="scss" scoped>
.unitWrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  // height: 100px;
  min-width: 48%;
  margin-bottom: 14px;
  &.wider {
    width: 200%;
  }
  .unitTop {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(260deg, #48a8ff 0%, #1470fa 100%);
    border-radius: 8px 8px 0px 0px;
    opacity: 0.87;
    padding: 10px 18px;
    .unitTitleContainer {
      display: flex;
      align-items: center;
      .unitFlag {
        width: 5px;
        height: 15px;
        background: #ffffff;
        border-radius: 3px;
        margin-right: 8px;
      }
      .unitTitle {
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        letter-spacing: 0.3px;
        color: #ffffff;
        line-height: 25px;
      }
    }

    .saveBtns {
      display: flex;
      height: 32px;
      align-items: center;
      justify-content: center;
      padding-right: 10px;
      .contentItemEditAndAIBtn {
        line-height: 32px;
        margin: 0 10px 0 15px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        display: flex;
        align-items: center;
        cursor: pointer;
        img {
          width: 22px;
          height: 22px;
        }
      }
      .saveEditBtn {
        width: 57px;
        height: 26px;
        color: #3674ff;
        background-color: #fff;
        border-radius: 4px;
        justify-content: center;
      }
    }
  }
  .allwrapper {
    overflow: auto;
    display: flex;
    width: 100%;
    border-radius: 0px 0px 8px 8px;
    border: 1px solid #c8cee9;
    //编辑状态下的！！
    &.inEdit {
      width: auto;
      .firstItem {
        width: auto !important;
      }
      .secondItem {
        width: auto !important;
        max-width: none !important;
      }
      .summaryContainer {
        max-width: none !important;
      }
      .itemForDisplay {
        width: auto !important;
        max-width: none !important;
      }
    }
    &.blueBorder {
      overflow: hidden;
      .unitContent {
        border: 1px solid #709cff;
      }
    }
    .unitContent {
      min-height: 280px;
      display: flex;
      background: #ffffff;
      flex: 1;
      &.colunmDirection {
        flex-direction: column; //改了这个图标就会没了不知道为什么，，，
        .itemForDisplay {
          max-width: 48%;
        }
      }
      .firstItem {
        display: flex;
        margin: 0 32px;
        width: 48%;
        flex: 1;

        .summary {
          max-width: 48%;
          width: 100%;
          padding-bottom: 30px;
          color: #999999;
          font-size: 14px;
          word-break: break-all;
          // overflow: hidden;
          // white-space: nowrap;
          // text-overflow: ellipsis;
          p {
            word-break: break-all;
            white-space: pre-wrap;
          }
          ::v-deep .el-textarea__inner {
            padding-top: 0;
          }
        }
        ::v-deep.el-textarea__inner {
          padding-right: 0;
        }
      }
      .secondItem {
        display: flex;
        // justify-content: center;
        // align-items: center;
        max-width: 48%;
        flex: 1;
        .itemForDisplay {
          display: flex;
          justify-content: center;
          align-items: center;
          flex: 1;
          width: 50%;
          padding: 0px 0px;
          min-width: 422px;
          // margin-left: 51px;
          flex-direction: column;
          .editTips {
            position: relative;
            font-size: 14px;
            font-family: PingFang-SC-Bold, PingFang-SC;
            color: #aaa;
            line-height: 28px;
            padding-bottom: 5px;
            padding-top: 8px;
            // bottom: -20px;
          }
        }
        .h100 {
          min-width: 422px;
          min-height: 362px;
          flex: 1;
        }
      }
      .summaryContainer {
        // max-width: 420px;
        width: 100%;
        padding-bottom: 26px;
        flex: 1;
        .summaryTitle {
          display: flex;
          align-items: center;
          height: 28px;
          font-size: 16px;
          font-family: PingFang-SC-Bold, PingFang-SC;
          font-weight: bold;
          color: #333333;
          line-height: 28px;
          .summaryFlag {
            display: inline-block;
            width: 7px;
            height: 7px;
            background: #b6deff;
            margin-right: 12px;
          }
        }
        .summaryContent {
          color: #999999;
          font-size: 14px;
          line-height: 28px;
          margin: 0;
        }
        ::v-deep .el-textarea__inner {
          padding-top: 0;
        }
      }
    }
    .itemForEdit {
      flex: 1;
      padding: 20px 0px 0px;
      // margin-left: 20px;
      &.inEdit {
        background: #f5f9ff;
      }
      .editBoxRight {
        flex: 1;
        padding: 12px 16px 12px 16px;
        font-size: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #4b6aaf;
        line-height: 27px;
        position: relative;
        border-radius: 0px 6px 6px 0px;
        min-height: 300px;
        padding-bottom: 20px;
        .extendsItem {
          position: relative;
          padding-bottom: 35px;
          padding: 12px 16px 12px 16px;
          .replaceByOne {
            display: flex;
            justify-content: flex-end;
            position: relative;
            bottom: 0;
            right: 14px;
            cursor: pointer;
            color: #4880ff;
          }
        }
      }
    }
  }
  ::v-deep .el-input__inner {
    height: 32px;
    background: #eeeeee;
    border-radius: 2px;
    font-size: 16px;
    font-family: PingFang-SC-Bold, PingFang-SC;
    font-weight: bold;
    color: #333333;
    line-height: 24px;
    outline: none;
  }
}
</style>
